const { success, badRequest, notFound, error } = require('../utils/response');
const cartModel = require('../models/cartModel');
const productModel = require('../models/productModel');

const getCart = async (req, res) => {
  try {
    const cart = await cartModel.getCartByUserId(req.userId);
    success(res, cart);
  } catch (err) {
    error(res, err.message);
  }
};

const addToCart = async (req, res) => {
  try {
    const { productId, quantity } = req.body;
    
    if (!productId || !quantity) {
      return badRequest(res, 'Please provide productId and quantity');
    }
    
    const product = await productModel.getProductById(productId);
    if (!product) {
      return notFound(res, 'Product not found');
    }
    
    const cart = await cartModel.addToCart(req.userId, productId, quantity);
    success(res, cart, 'Item added to cart');
  } catch (err) {
    error(res, err.message);
  }
};

const updateCartItem = async (req, res) => {
  try {
    const { productId } = req.params;
    const { quantity } = req.body;
    
    if (!quantity) {
      return badRequest(res, 'Please provide quantity');
    }
    
    const product = await productModel.getProductById(productId);
    if (!product) {
      return notFound(res, 'Product not found');
    }
    
    const cart = await cartModel.updateCartItem(req.userId, productId, quantity);
    success(res, cart, 'Cart updated');
  } catch (err) {
    error(res, err.message);
  }
};

const removeFromCart = async (req, res) => {
  try {
    const { productId } = req.params;
    
    const product = await productModel.getProductById(productId);
    if (!product) {
      return notFound(res, 'Product not found');
    }
    
    const cart = await cartModel.removeFromCart(req.userId, productId);
    success(res, cart, 'Item removed from cart');
  } catch (err) {
    error(res, err.message);
  }
};

module.exports = {
  getCart,
  addToCart,
  updateCartItem,
  removeFromCart
};